#!/usr/bin/python2.3
from __future__ import division
import re, archdesc

def loadmatlab(file, old=False):
  print "Loading Matlab dataset " + file

  if old:
    eq = re.compile("A\{(.*), (.*)\} = (.*);")
  else:
    eq = re.compile("A\{(.*), (.*), 1\} = (.*);")

  LPP = dict()
  LPA = dict()

  f = open(file, 'r')
  for l in f.readlines():
    m = eq.match(l)
    if m:
      if not int(m.group(1)) in LPP:
        pp = [0, 0, 0]
        pa = ''
      else:
        pp = LPP[int(m.group(1))]
        pa = LPA[int(m.group(1))]
      
      if int(m.group(2)) < 4:
        pp[int(m.group(2))-1] = float(m.group(3))
      else:
        pa = m.group(3)[1:-1]
        
      LPP[int(m.group(1))] = pp
      LPA[int(m.group(1))] = pa
  f.close()
  
  return (LPP.values(), LPA.values())

def loadascii(file):
  print "Loading ASCII dataset " + file
  PP = []
  PA = []

  f = open(file, 'r')
  for l in f.readlines():
    w = l.split(" ")
    PP.append([float(w[0]), float(w[1]), float(w[2])])
    PA.append(" ".join(w[3:]))
  f.close()
  
  return (PP, PA)

def dominates(a, b):
  if a == b:
    return False
     
  for (x, y) in zip(a, b):
    if y < x:
      return False
                  
  return True

def unique(P):
  PI = []
  D = dict()
  
  i = 0
  for p in P:
    if not tuple(p) in D:
      D[tuple(p)] = 0
      PI.append(i)
    
    i = i + 1

  return PI

def getpareto(P, limits):
  print "Computing Pareto set"
  PI = []
  U = unique(P)
  
  i = 0
  for i in U:
    pareto = True

    for l in range(len(limits)):
      if P[i][l] > limits[l]:
        pareto = False
        break

    if pareto:
      for j in U:
        if dominates(P[j], P[i]):
          pareto = False
          break
    
    if pareto:
      PI.append(i)
    
    i = i + 1
 
  return PI

def select(L, I):
  NL = []
  for i in I:
    NL.append(L[i])
    
  return NL
